<template>
  <div class="content-wrapper">
    <div class="top-search-box top-search-height">
      <a-form :model="queryForm" :label-col="{ flex: '0 0 120px' }" :wrapper-col="{ flex: '1 1 0' }">
        <a-row>
          <a-col :span="6">
            <a-form-item name="name" label="name">
              <a-input v-model:value="queryForm.name" placeholder="请输入name" />
            </a-form-item>
          </a-col>
          <a-col style="margin-left: auto" :span="6">
            <div class="table-page-search-submitButtons">
              <a-space>
                <AvicAdvancedQueryButton
                  table-key="my111"
                  :query-form="queryForm"
                  :advanced="advanced"
                  @select="
                    (value, advancedFlag) => {
                      queryForm = value;
                      advanced = !advanced ? advancedFlag : advanced;
                    }
                  "
                  @search="handleQuery"
                />
                <a-button type="primary" ghost title="重置" @click="resetQuery">
                  <template #icon><RedoOutlined /></template>
                  重置
                </a-button>
                <a-button type="link" @click="toggleAdvanced">
                  {{ advanced ? '收起' : '展开' }}
                  <UpOutlined v-if="advanced" />
                  <DownOutlined v-else />
                </a-button>
              </a-space>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-wrapper">
      <AvicTable
        ref="my111Ref"
        table-key="my111TableKey"
        :row-key="(record) => record.id"
        :data-source="list"
        :loading="loading"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          columnWidth: 40,
          fixed: true
        }"
        :show-custom-page-size="true"
        :page-parameter="queryParam.pageParameter"
        :total="totalPage"
        :columns="columns"
        @change="handleTableChange"
        @refresh="getList"
      >
        <template #toolBarLeft>
          <div style="flex: 1; display: flex; gap: 8px">
            <a-button v-hasPermi="['my111:add']" type="primary" title="添加" @click="handleAdd">
              <template #icon><PlusOutlined /></template>
              添加
            </a-button>
            <a-button
              v-hasPermi="['my111:delete']"
              :type="selectedRowKeys.length == 0 ? 'default' : 'primary'"
              danger
              :loading="delLoading"
              title="删除"
              @click="handleDelete(selectedRowKeys, '')"
            >
              <template #icon><DeleteOutlined /></template>
              删除
            </a-button>
            <a-button v-hasPermi="['my111:import']" type="primary" ghost title="导入" @click="handleImport">
              <template #icon><ImportOutlined /></template>
              导入
            </a-button>
            <a-button v-hasPermi="['my111:export']" type="primary" ghost title="导出" @click="handleExport">
              <template #icon><ExportOutlined /></template>
              导出
            </a-button>
          </div>
        </template>
        <template #bodyCell="{ column, text, record, index }">
          <template v-if="column.dataIndex === 'id'">
            {{ index + 1 + queryParam.pageParameter.rows * (queryParam.pageParameter.page - 1) }}
          </template>
          <template v-if="column.dataIndex === 'name'">
            <a @click="handleDetail(record)">
              {{ record.name }}
            </a>
          </template>
          <template v-if="column.dataIndex === 'secretLevelName'">
            <AvicDictTag :value="text" :options="lookupList?.PLATFORM_FILE_SECRET_LEVEL" />
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-button
              v-hasPermi="['my111:edit']"
              type="link"
              title="编辑"
              class="inner-btn"
              @click.stop="
                (event) => {
                  handleEdit(record.id);
                }
              "
            >
              编辑
            </a-button>
            <a-button
              v-hasPermi="['my111:delete']"
              type="link"
              title="删除"
              danger
              class="inner-btn"
              @click.stop="
                (event) => {
                  handleDelete([record.id], 'row');
                }
              "
            >
              删除
            </a-button>
          </template>
        </template>
      </AvicTable>
    </div>
  </div>
  <!-- 添加页面弹窗 -->
  <My111Add v-if="showAddModal" ref="my111AddModal" @reloadData="getList" @close="showAddModal = false" />
  <!-- 编辑页面弹窗 -->
  <My111Edit v-if="showEditModal" ref="my111EditModal" :form-id="formId" @reloadData="getList" @close="showEditModal = false" />
  <!-- 详细页面弹窗 -->
  <My111Detail v-if="showDetailModal" ref="my111DetailModal" :form-id="formId" @close="showDetailModal = false" />
  <AvicExcelImport
    v-if="showImportModal"
    :form-data="excelParams"
    title="导入"
    :import-url="basePath + '/import-data/v1'"
    :download-template-url="basePath + '/download-template/v1'"
    :body-style="{ padding: '4px' }"
    @reloadData="getList"
    @close="showImportModal = false"
  />
</template>
<script lang="ts" setup>
// 引入模块DTO
import type { My111Dto } from '@/api/avic/tlk/poart/demo/My111Api';
// 引入模块API
import { listMy111ByPage, delMy111, exportExcel, basePath } from '@/api/avic/tlk/poart/demo/My111Api';
// 引入添加页面组件
import My111Add from './My111Add.vue';
// 引入编辑页面组件
import My111Edit from './My111Edit.vue';
// 引入详情页面组件
import My111Detail from './My111Detail.vue';
import { useLookup } from '@/utils/hooks/useLookup';
const { proxy } = getCurrentInstance();
const columns = [
  {
    title: 'name',
    dataIndex: 'name',
    ellipsis: true,
    width: 200,
    resizable: true,
    align: 'left'
  },
  {
    title: '密级',
    dataIndex: 'secretLevelName',
    ellipsis: true,
    minWidth: 100,
    resizable: true,
    customHeaderCell() {
      return {
        ['class']: 'required-table-title'
      };
    },
    align: 'left'
  },
  {
    title: '操作',
    dataIndex: 'action',
    ellipsis: true,
    width: 107,
    fixed: 'right'
  }
];
const queryForm = ref<My111Dto>({});
const queryParam = reactive({
  // 请求表格数据参数
  pageParameter: {
    page: 1, // 页数
    rows: proxy.$settings.table.pageSize || 20 // 每页条数
  },
  searchParams: {
    ...queryForm.value
  },
  keyWord: ref(''), // 快速查询数据
  sidx: null, // 排序字段
  sord: null // 排序方式: desc降序 asc升序
});
const { lookupList } = useLookup(['PLATFORM_FILE_SECRET_LEVEL']);
const showAddModal = ref(false); // 是否展示添加弹窗
const showEditModal = ref(false); // 是否展示编辑弹窗
const showImportModal = ref(false); // 是否展示导入弹窗
// 必填参数tableName全局唯一，与tableKey保持一致
const excelParams = ref({
  tableName: 'my111'
});
const advanced = ref(false); // 高级搜索 展开/关闭
const list = ref([]); // 表格数据集合
const formId = ref(''); // 当前行数据id
const selectedRowKeys = ref([]); // 选中数据主键集合
const selectedRows = ref([]); // 选中行集合
const loading = ref(false); // 页面初始化时锁屏
const delLoading = ref(false); // 删除时锁屏
const totalPage = ref(0); // 总页数
const showDetailModal = ref(false); // 是否展示详情弹窗
onMounted(() => {
  // 加载表格数据
  getList();
});

/** 查询数据 */
function getList() {
  selectedRowKeys.value = [];
  // 清空选中
  selectedRows.value = [];
  list.value = [];
  loading.value = true;
  listMy111ByPage(queryParam)
    .then((response) => {
      list.value = response.data.result;
      totalPage.value = response.data.pageParameter.totalCount;
      queryParam.pageParameter.page = response.data.pageParameter.page;
      loading.value = false;
    })
    .catch(() => {
      list.value = [];
      totalPage.value = 0;
      loading.value = false;
    });
}

/** 高级查询 查询按钮操作 */
function handleQuery() {
  queryParam.searchParams = queryForm.value;
  queryParam.keyWord = '';
  queryParam.pageParameter.page = 1;
  getList();
}

/** 高级查询 重置按钮操作 */
function resetQuery() {
  queryForm.value = {};
  handleQuery();
}

/** 高级查询 展开/收起 */
function toggleAdvanced() {
  advanced.value = !advanced.value;
}

/** 添加 */
function handleAdd() {
  showAddModal.value = true;
}

/** 编辑 */
function handleEdit(id) {
  formId.value = id;
  showEditModal.value = true;
}

/** 详情 */
function handleDetail(record) {
  formId.value = record.id;
  showDetailModal.value = true;
}

/** 删除 */
function handleDelete(ids, type) {
  if (ids.length === 0) {
    proxy.$message.warning('请选择要删除的数据！');
    return;
  }
  proxy.$confirm({
    title: `确认要删除${type === 'row' ? '当前行的' : '已选数据'}数据吗?`,
    okText: '确定',
    cancelText: '取消',
    centered: true,
    onOk: () => {
      delLoading.value = true;
      delMy111(ids)
        .then((response) => {
          if (response.success) {
            proxy.$message.success('删除成功！');
            // 清空选中
            selectedRowKeys.value = [];
            selectedRows.value = [];
            getList();
          }
          delLoading.value = false;
        })
        .catch(() => {
          delLoading.value = false;
        });
    }
  });
}

/** 导入 */
function handleImport() {
  showImportModal.value = true;
}

/** 导出 */
function handleExport() {
  proxy.$confirm({
    title: '确认导出数据吗?',
    okText: '确定',
    cancelText: '取消',
    centered: true,
    onOk: () => {
      loading.value = true;
      queryParam.searchParams = queryForm.value;
      exportExcel(queryParam).then(() => {
        loading.value = false;
        proxy.$message.info('导出成功');
      });
    }
  });
}

/** 勾选复选框时触发 */
function onSelectChange(rowKeys, rows) {
  selectedRowKeys.value = rowKeys;
  selectedRows.value = rows;
}

/** 表头排序 */
function handleTableChange(pagination, _filters, sorter) {
  queryParam.pageParameter.page = pagination.current;
  queryParam.pageParameter.rows = pagination.pageSize;
  if (proxy.$objIsNotBlank(sorter.field)) {
    queryParam.sidx = sorter.field;
    queryParam.sord = sorter.order === 'ascend' ? 'asc' : 'desc';
  }
  getList();
}
</script>
